package org.stvd.repository.admin.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.UserDep;
import org.stvd.repository.admin.UserDepDao;
import org.stvd.repository.base.impl.BaseDaoImpl;

/**
 * @Title UserDepDaoImpl
 * @Destribution 用户机构映射数据层接口实现类 
 * @author houzx
 * @date 2020年4月9日
 */
@Repository("UserDepDao")
public class UserDepDaoImpl extends BaseDaoImpl<UserDep> implements UserDepDao {

    @Override
    public List<UserDep> findUserDepByUid(String userId, String guid) {
        return findByHQL("from UserDep T where T.userId= ?0 and T.guid = ?1", userId, guid);
    }

    @Override
    public List<UserDep> findUserDepByDepid(String depId, String guid) {
        return findByHQL("from UserDep T where T.depId= ?0 and T.guid = ?1", depId, guid);
    }
    
    @Override
    @Transactional
    public void insert(String userId, String[] depIds, String guid) {
        em.createQuery("delete from UserDep where userId = :userId and guid = :guid")
        .setParameter("userId", userId)
        .setParameter("guid", guid)
        .executeUpdate();
        em.flush();
        if (depIds != null) {
            for (String depId : depIds) {
                UserDep userdepTmp = new UserDep();
                userdepTmp.setId(StringUtil.getRandomUUID());
                userdepTmp.setUserId(userId);
                userdepTmp.setDepId(depId);
                userdepTmp.setGuid(guid);
                insert(userdepTmp);
            }
        }
    }

    @Override
    public UserDep getUserDepByDepCode(String userId, String depCode, String guid) {
        String hql = "SELECT T1 FROM UserDep T1, Department T2 WHERE T1.depId = T2.depId "
                + " AND T1.userId = ?0 AND T2.depCode = ?1 AND T2.guid = ?2";
        List<UserDep> list = findByHQL(hql, userId, depCode, guid);
        if(list!=null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    @Transactional
    public void deleteUserDepMap(String userId, String depCode, String guid) {
        String sql = "DELETE FROM user_dep WHERE user_id = :userId AND guid = :guid"
                + " AND dep_id IN ("
                + " SELECT dep_id FROM department WHERE dep_code = :depCode AND guid = :guid)";
        Query query = em.createNativeQuery(sql);
        query.setParameter("userId", userId);
        query.setParameter("guid", guid);
        query.setParameter("depCode", depCode);
        query.executeUpdate();
        em.flush();
    }
}
